<template>
  <div class="task-detail-container" v-loading="loading">
    <div v-if="task">
      <el-page-header @back="goBack" :title="task.title" class="page-header"/>
      
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card class="task-card">
            <template #header>
              <div class="card-header">
                <h3>{{ task.title }}</h3>
                <el-tag :type="getStatusType(task.status)" size="large">{{ getStatusText(task.status) }}</el-tag>
              </div>
            </template>
            
            <div class="task-info">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="发布企业">{{ task.companyName }}</el-descriptions-item>
                <el-descriptions-item label="任务类型">{{ task.jobType || '未指定' }}</el-descriptions-item>
                <el-descriptions-item label="工作地点">{{ task.location }}</el-descriptions-item>
                <el-descriptions-item label="工作时间">{{ formatDate(task.startTime) }} 至 {{ formatDate(task.endTime) }}</el-descriptions-item>
                <el-descriptions-item label="报酬">
                  <span class="salary">{{ task.salary }} 元</span>
                </el-descriptions-item>
                <el-descriptions-item label="发布时间">{{ formatDate(task.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="任务内容">
                  <div class="task-content">{{ task.content }}</div>
                </el-descriptions-item>
              </el-descriptions>
            </div>
            
            <!-- 企业用户操作区域 -->
            <div v-if="isCompanyUser" class="user-operations">
              <!-- 任务发布者操作 -->
              <div v-if="isTaskOwner" class="owner-actions">
                <div class="section-title">任务管理</div>
                <div class="task-actions">
                  <!-- 已发布状态 -->
                  <el-button 
                    v-if="task.status === 'published'"
                    type="danger" 
                    @click="handleCancelTask"
                    :icon="Delete">
                    撤销任务
                  </el-button>
                  
                  <!-- 已分配状态 -->
                  <el-button 
                    v-if="task.status === 'assigned'"
                    type="success" 
                    @click="handleCompleteTask"
                    :icon="Check">
                    结算任务
                  </el-button>
                  
                  <!-- 待确认完成状态 -->
                  <el-button 
                    v-if="task.status === 'pending_completion'"
                    type="success" 
                    @click="handleCompleteTask"
                    :icon="Check">
                    确认完成
                  </el-button>
                  
                  <el-button 
                    v-if="task.status === 'assigned' || task.status === 'pending_completion'"
                    type="warning" 
                    @click="handleTerminateTask"
                    :icon="CloseBold">
                    中止任务
                  </el-button>
                  
                  <!-- 通用操作 -->
                  <el-button 
                    type="primary" 
                    @click="openMessageDialog"
                    :icon="Message"
                    :disabled="!hasApplications">
                    发送消息
                  </el-button>
                  
                  <el-button 
                    type="info" 
                    @click="handleContactSupport"
                    :icon="Service">
                    求助客服
                  </el-button>
                </div>
              </div>
              
              <!-- 非任务发布者的企业用户 -->
              <div v-else class="non-owner-actions">
                <div class="section-title">任务详情</div>
                <el-alert
                  title="您正在查看其他企业发布的任务"
                  type="info"
                  :closable="false"
                  class="mb-10">
                </el-alert>
                <!-- 仅允许查看操作 -->
                <div class="task-actions">
                  <el-button 
                    type="info" 
                    @click="handleContactSupport"
                    :icon="Service">
                    求助客服
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- 零工用户操作区域 -->
            <div v-else-if="isWorkerUser" class="user-operations">
              <div class="section-title">任务操作</div>
              <div class="task-status-info mb-10">
                <el-tag v-if="task.isApplied" type="warning">您已申请此任务</el-tag>
                <el-tag v-else-if="task.status === 'published'" type="info">可申请任务</el-tag>
                <el-tag v-else type="info">此任务当前无法申请</el-tag>
              </div>
              
              <div class="task-actions">
                <!-- 未申请且任务状态为已发布 -->
                <el-button 
                  v-if="task.status === 'published' && !task.isApplied"
                  type="primary" 
                  @click="handleApplyTask"
                  :icon="Check">
                  申请任务
                </el-button>
                
                <!-- 已申请但未被接受 -->
                <el-button 
                  v-if="task.status === 'published' && task.isApplied && task.applicationStatus === 'pending'"
                  type="danger" 
                  @click="handleCancelApplyTask"
                  :icon="Close">
                  取消申请
                </el-button>
                
                <!-- 任务已分配给当前零工，可以标记完成 -->
                <el-button 
                  v-if="task.status === 'assigned' && task.applicationStatus === 'accepted'"
                  type="success" 
                  @click="handleWorkerCompleteTask"
                  :icon="Check">
                  标记任务完成
                </el-button>
                
                <!-- 待确认完成状态提示 -->
                <el-tag 
                  v-if="task.status === 'pending_completion' && task.applicationStatus === 'accepted'"
                  type="warning">
                  已提交完成，等待企业确认
                </el-tag>
                
                <!-- 通用操作 - 只有当任务已分配给当前零工用户时才显示发送消息按钮 -->
                <el-button 
                  v-if="task.status === 'assigned' && task.applicationStatus === 'accepted'"
                  type="primary" 
                  @click="openMessageDialog"
                  :icon="Message">
                  发送消息
                </el-button>
                
                <el-button 
                  type="info" 
                  @click="handleContactSupport"
                  :icon="Service">
                  求助客服
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <!-- 申请列表 (仅企业用户可见) -->
          <el-card v-if="isCompanyUser && isTaskOwner" class="applications-card">
            <template #header>
              <div class="card-header">
                <h3>申请列表</h3>
                <el-tag type="info" v-if="applications.length === 0">暂无申请</el-tag>
                <el-tag type="warning" v-else-if="applications.some(app => app.status === 'pending')">
                  <el-badge :value="applications.filter(app => app.status === 'pending').length" :max="99">
                    待处理申请
                  </el-badge>
                </el-tag>
                <el-tag type="success" v-else>{{ applications.length }}人申请</el-tag>
              </div>
            </template>
            
            <div v-if="applications.length > 0">
              <el-alert
                v-if="applications.some(app => app.status === 'pending')"
                type="warning"
                :closable="false"
                show-icon
                title="您有待处理的申请"
                description="请及时处理零工用户的申请"
                class="mb-10"
              />
              
              <el-alert
                type="info"
                :closable="true"
                show-icon
                title="申请处理提示"
                description="一旦您接受某个零工的申请，任务状态将变为'已分配'，其他申请将自动被拒绝。您可以查看每个申请详情后再决定是否接受。"
                class="mb-10"
              />
              
              <el-collapse accordion>
                <el-collapse-item 
                  v-for="app in applications" 
                  :key="app.id" 
                  :title="app.workerName"
                  :name="app.id"
                >
                  <template #title>
                    <div class="application-item-title">
                      <span>{{ app.workerName }}</span>
                      <el-tag 
                        :type="getApplicationStatusType(app.status)" 
                        size="small"
                        effect="plain"
                        class="ml-10"
                      >
                        {{ getApplicationStatusText(app.status) }}
                      </el-tag>
                      <el-tag 
                        v-if="app.status === 'pending'" 
                        type="danger" 
                        size="small"
                        class="ml-5"
                      >
                        新申请
                      </el-tag>
                    </div>
                  </template>
                  <div class="application-item">
                    <div class="application-item-info">
                      <p><strong>申请时间：</strong>{{ formatDate(app.createTime) }}</p>
                      <p><strong>状态：</strong>
                        <el-tag :type="getApplicationStatusType(app.status)">
                          {{ getApplicationStatusText(app.status) }}
                        </el-tag>
                      </p>
                      <div class="application-actions" v-if="app.status === 'pending'">
                        <el-button 
                          type="primary" 
                          size="small" 
                          @click="handleAcceptApplication(app.id)"
                        >
                          接受申请
                        </el-button>
                        <el-button 
                          type="danger" 
                          size="small" 
                          @click="handleRejectApplication(app.id)"
                        >
                          拒绝申请
                        </el-button>
                      </div>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
            
            <el-empty v-else description="暂无申请" />
          </el-card>
          
          <!-- 零工用户申请状态卡片 -->
          <el-card v-if="isWorkerUser && task.isApplied" class="application-status-card">
            <template #header>
              <div class="card-header">
                <h3>申请状态</h3>
              </div>
            </template>
            
            <div class="application-status">
              <el-result
                :icon="getApplicationResultIcon(task.applicationStatus)"
                :title="getApplicationResultTitle(task.applicationStatus)"
                :sub-title="getApplicationResultSubtitle(task.applicationStatus)">
              </el-result>
            </div>
          </el-card>
          
          <!-- 任务申请状态卡片（对所有用户可见） -->
          <el-card class="task-application-status-card">
            <template #header>
              <div class="card-header">
                <h3>申请情况</h3>
              </div>
            </template>
            
            <div class="task-application-status">
              <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="申请人数">
                  <el-tag type="info" effect="plain">{{ applications.length || 0 }}人</el-tag>
                </el-descriptions-item>
                
                <el-descriptions-item label="申请状态">
                  <el-tag 
                    v-if="task.status === 'published' && applications.length === 0" 
                    type="info" 
                    effect="plain">尚无人申请</el-tag>
                  <el-tag 
                    v-else-if="task.status === 'published' && applications.length > 0" 
                    type="warning" 
                    effect="plain">有{{ applications.length }}人申请，待处理</el-tag>
                  <el-tag 
                    v-else-if="task.status === 'assigned'" 
                    type="success" 
                    effect="plain">已有人被接受</el-tag>
                  <el-tag 
                    v-else-if="task.status === 'completed'" 
                    type="info" 
                    effect="plain">任务已完成</el-tag>
                  <el-tag 
                    v-else-if="task.status === 'cancelled'" 
                    type="danger" 
                    effect="plain">任务已取消</el-tag>
                </el-descriptions-item>
                
                <el-descriptions-item v-if="task.status === 'assigned' || task.status === 'completed'" label="执行人">
                  <span>{{ task.assignedWorkerName || '未知' }}</span>
                </el-descriptions-item>
                
                <el-descriptions-item label="可申请状态">
                  <el-tag 
                    v-if="task.status === 'published'" 
                    type="success" 
                    effect="plain">可申请</el-tag>
                  <el-tag v-else type="info" effect="plain">不可申请</el-tag>
                </el-descriptions-item>
                
                <el-descriptions-item v-if="isWorkerUser && !task.isApplied && task.status === 'published'" label="操作">
                  <el-button type="primary" size="small" @click="handleApplyTask">申请任务</el-button>
                </el-descriptions-item>
                
                <el-descriptions-item v-if="isWorkerUser && task.isApplied" label="我的申请">
                  <el-tag :type="getApplicationStatusType(task.applicationStatus)">
                    {{ getApplicationStatusText(task.applicationStatus) }}
                  </el-tag>
                  <div class="mt-5" v-if="task.applicationStatus === 'pending'">
                    <el-button type="danger" size="small" @click="handleCancelApplyTask">取消申请</el-button>
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-card>
          
          <!-- 任务状态时间线 -->
          <el-card class="timeline-card">
            <template #header>
              <div class="card-header">
                <h3>任务状态</h3>
              </div>
            </template>
            
            <el-timeline>
              <el-timeline-item
                timestamp="任务发布"
                :type="getTimelineItemType('published', task.status)"
                :hollow="getTimelineItemHollow('published', task.status)"
              >
                <h4>发布</h4>
                <p>{{ formatDate(task.createTime) }}</p>
              </el-timeline-item>
              
              <el-timeline-item
                timestamp="任务分配"
                :type="getTimelineItemType('assigned', task.status)"
                :hollow="getTimelineItemHollow('assigned', task.status)"
              >
                <h4>分配</h4>
                <p v-if="task.status === 'assigned' || task.status === 'completed'">
                  已分配给零工
                </p>
                <p v-else>等待分配</p>
              </el-timeline-item>
              
              <el-timeline-item
                timestamp="任务完成"
                :type="getTimelineItemType('completed', task.status)"
                :hollow="getTimelineItemHollow('completed', task.status)"
              >
                <h4>完成</h4>
                <p v-if="task.status === 'completed'">
                  任务已完成
                </p>
                <p v-else>等待完成</p>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <el-empty v-else-if="!loading" description="任务不存在或已被删除" />
    
    <!-- 发送消息对话框 -->
    <el-dialog
      v-model="messageDialogVisible"
      title="发送消息"
      width="500px"
    >
      <el-form :model="messageForm" ref="messageFormRef" :rules="messageRules">
        <!-- 隐藏接收者选择，改为显示接收者名称 -->
        <el-form-item label="接收者">
          <el-tag size="medium">{{ getReceiverName() }}</el-tag>
          <!-- 隐藏字段仍然保留数据 -->
          <input type="hidden" v-model="messageForm.receiverId" />
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入消息内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="messageDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSendMessage">发送</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTaskDetail, cancelTask, applyTask, cancelApplyTask, acceptApplication, rejectApplication, completeTask, terminateTask, workerCompleteTask } from '@/api/task'
import { sendMessage } from '@/api/message'
import { formatDate } from '@/utils/format'
import { Delete, Check, CloseBold, Message, Service, Close, Warning, CircleCheck, CircleClose } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const task = ref(null)
const applications = ref([])
const userType = ref(localStorage.getItem('userType') || 'worker')
const messageDialogVisible = ref(false)
const messageFormRef = ref(null)

// 创建默认的消息表单
const createDefaultMessageForm = () => {
  return {
    receiverId: null,
    taskId: null,
    content: ''
  }
}

const messageForm = ref(createDefaultMessageForm())
const messageRules = {
  receiverId: [
    { required: true, message: '请选择接收者', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' }
  ]
}

// 计算属性：用户类型判断
const isCompanyUser = computed(() => userType.value === 'company')
const isWorkerUser = computed(() => userType.value === 'worker')
const isTaskOwner = computed(() => task.value?.isOwner === true)
const hasApplications = computed(() => applications.value && applications.value.length > 0)

const loadTaskDetail = async () => {
  loading.value = true
  try {
    const taskId = route.params.id
    console.log('正在加载任务详情，ID:', taskId)
    console.log('当前用户类型:', userType.value)
    
    // 初始化消息表单
    messageForm.value = {
      ...createDefaultMessageForm(),
      taskId: Number(taskId)
    }
    
    const response = await getTaskDetail(taskId)
    console.log('任务详情API响应:', response)
    
    // 处理响应数据
    if (response && typeof response === 'object' && response.id && response.title) {
      task.value = response
      console.log('使用直接返回的任务对象')
    } else if (response && response.data) {
      task.value = response.data
      console.log('从response.data获取任务对象')
    } else {
      console.error('无法解析任务数据:', response)
      throw new Error('获取任务详情失败，数据格式不正确')
    }
    
    // 设置默认值，确保UI不会因为缺少属性而出错
    if (task.value) {
      task.value.isOwner = task.value.isOwner || false
      task.value.isApplied = task.value.isApplied || false
      task.value.applicationStatus = task.value.applicationStatus || 'unknown'
      task.value.assignedWorkerName = task.value.assignedWorkerName || ''
      
      // 如果任务状态是已分配或已完成，但没有分配的工人名称，尝试从申请列表中获取
      if ((task.value.status === 'assigned' || task.value.status === 'completed') && !task.value.assignedWorkerName) {
        // 寻找被接受的申请
        const acceptedApp = task.value.applications?.find(app => app.status === 'accepted')
        if (acceptedApp) {
          task.value.assignedWorkerName = acceptedApp.workerName
        }
      }
      
      // 更新申请列表
      if (task.value.applications) {
        applications.value = task.value.applications
        console.log('申请列表更新，数量:', applications.value.length)
        
        // 如果是零工用户，检查自己的申请状态
        if (isWorkerUser.value) {
          const currentUserId = localStorage.getItem('userId')
          const myApplication = applications.value.find(app => app.workerId == currentUserId)
          if (myApplication) {
            task.value.isApplied = true
            task.value.applicationStatus = myApplication.status
            console.log('找到当前用户的申请，状态:', myApplication.status)
          }
        }
      }
      
      // 如果是零工用户，设置消息接收者为任务发布者
      if (isWorkerUser.value) {
        messageForm.value.receiverId = task.value.companyId
      }
    }
    
    // 详细调试信息
    console.log('任务详情加载完成:', {
      id: task.value.id,
      title: task.value.title,
      status: task.value.status,
      isOwner: task.value.isOwner,
      isApplied: task.value.isApplied,
      applicationStatus: task.value.applicationStatus,
      companyId: task.value.companyId,
      applicationsCount: task.value.applications?.length || 0
    })
  } catch (error) {
    console.error('加载任务详情失败:', error)
    ElMessage.error(error.message || '获取任务详情失败')
    task.value = null
  } finally {
    loading.value = false
  }
}

const getStatusType = (status) => {
  switch (status) {
    case 'published': return 'primary'
    case 'assigned': return 'success'
    case 'completed': return 'info'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'published': return '已发布'
    case 'assigned': return '已分配'
    case 'pending_completion': return '待确认完成'
    case 'completed': return '已完成'
    case 'cancelled': return '已取消'
    default: return '未知状态'
  }
}

const getApplicationStatusType = (status) => {
  switch (status) {
    case 'pending': return 'warning'
    case 'accepted': return 'success'
    case 'rejected': return 'danger'
    case 'cancelled': return 'info'
    default: return 'info'
  }
}

const getApplicationStatusText = (status) => {
  switch (status) {
    case 'pending': return '待处理'
    case 'accepted': return '已接受'
    case 'rejected': return '已拒绝'
    case 'cancelled': return '已取消'
    default: return '未知状态'
  }
}

// 申请结果图标
const getApplicationResultIcon = (status) => {
  switch (status) {
    case 'pending': return Warning
    case 'accepted': return CircleCheck
    case 'rejected': return CircleClose
    case 'cancelled': return Close
    default: return 'info'
  }
}

// 申请结果标题
const getApplicationResultTitle = (status) => {
  switch (status) {
    case 'pending': return '申请处理中'
    case 'accepted': return '申请已接受'
    case 'rejected': return '申请已拒绝'
    case 'cancelled': return '申请已取消'
    default: return '未知状态'
  }
}

// 申请结果副标题
const getApplicationResultSubtitle = (status) => {
  switch (status) {
    case 'pending': return '您的申请正在等待企业处理'
    case 'accepted': return '恭喜！企业已接受您的申请'
    case 'rejected': return '很遗憾，企业拒绝了您的申请'
    case 'cancelled': return '您已取消此任务申请'
    default: return '申请状态未知'
  }
}

const getTimelineItemType = (step, currentStatus) => {
  const statusOrder = {
    'published': 1,
    'assigned': 2,
    'completed': 3,
    'cancelled': 0
  }
  
  const stepOrder = {
    'published': 1,
    'assigned': 2,
    'completed': 3
  }
  
  // 如果当前状态是已取消，使用灰色
  if (currentStatus === 'cancelled') {
    return 'info'
  }
  
  // 如果当前步骤小于等于当前状态顺序，显示为主色
  if (stepOrder[step] <= statusOrder[currentStatus]) {
    return 'primary'
  }
  
  // 否则显示为灰色
  return 'info'
}

const getTimelineItemHollow = (step, currentStatus) => {
  const statusOrder = {
    'published': 1,
    'assigned': 2,
    'completed': 3,
    'cancelled': 0
  }
  
  const stepOrder = {
    'published': 1,
    'assigned': 2,
    'completed': 3
  }
  
  // 如果当前步骤小于当前状态顺序，显示为实心
  if (stepOrder[step] < statusOrder[currentStatus]) {
    return false
  }
  
  // 如果当前步骤等于当前状态顺序，显示为实心
  if (stepOrder[step] === statusOrder[currentStatus]) {
    return false
  }
  
  // 否则显示为空心
  return true
}

const goBack = () => {
  router.back()
}

const handleCancelTask = async () => {
  try {
    await ElMessageBox.confirm('确定要撤销该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await cancelTask(task.value.id)
    if (response.data) {
      ElMessage.success('任务已撤销')
      loadTaskDetail()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '撤销任务失败')
    }
  }
}

const handleCompleteTask = async () => {
  try {
    await ElMessageBox.confirm('确定要结算该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await completeTask(task.value.id)
    if (response.data) {
      ElMessage.success('任务已结算完成')
      loadTaskDetail()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '结算任务失败')
    }
  }
}

const handleTerminateTask = async () => {
  try {
    await ElMessageBox.confirm('确定要中止该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await terminateTask(task.value.id)
    if (response && (response.data === true || response.data === 'true' || response.code === 200)) {
      ElMessage.success('任务已中止')
      loadTaskDetail() // 重新加载任务详情
    } else {
      throw new Error('中止任务失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '中止任务失败')
    }
  }
}

const handleContactSupport = () => {
  ElMessage.info('正在跳转至客服页面...')
  router.push('/support')
}

const handleAcceptApplication = async (applicationId) => {
  try {
    await ElMessageBox.confirm('确定要接受该申请吗？接受后任务将分配给该零工，其他申请将被自动拒绝。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 显示加载状态
    loading.value = true;
    
    const response = await acceptApplication(applicationId)
    if (response && (response.data === true || response.data === 'true' || response.code === 200)) {
      ElMessage.success('已接受申请')
      
      // 更新本地状态
      const acceptedApp = applications.value.find(app => app.id === applicationId)
      if (acceptedApp) {
        // 更新状态为已接受
        acceptedApp.status = 'accepted'
        
        // 更新任务状态为已分配
        task.value.status = 'assigned'
        
        // 设置任务的执行人
        task.value.assignedWorkerName = acceptedApp.workerName
        
        // 其他申请标记为已拒绝
        applications.value.forEach(app => {
          if (app.id !== applicationId && app.status === 'pending') {
            app.status = 'rejected'
          }
        })
        
        // 如果该任务是当前用户申请的任务，更新自己的申请状态
        if (task.value.isApplied && acceptedApp.workerId === localStorage.getItem('userId')) {
          task.value.applicationStatus = 'accepted'
        }
        
        // 自动发送通知消息给被接受的零工
        try {
          const messageData = {
            receiverId: Number(acceptedApp.workerId),
            taskId: Number(task.value.id),
            content: `恭喜您！您申请的任务"${task.value.title}"已被接受，请及时与我们联系，了解更多详情。`
          }
          await sendMessage(messageData)
          console.log('自动发送接受申请通知消息成功')
        } catch (msgError) {
          console.error('自动发送接受申请通知消息失败:', msgError)
          // 不中断流程
        }
      }
      
      // 重新加载任务详情
      loadTaskDetail()
    } else {
      throw new Error('接受申请失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '接受申请失败')
    }
  } finally {
    loading.value = false;
  }
}

const handleRejectApplication = async (applicationId) => {
  try {
    await ElMessageBox.confirm('确定要拒绝该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await rejectApplication(applicationId)
    if (response && (response.data === true || response.data === 'true' || response.code === 200)) {
      ElMessage.success('已拒绝申请')
      loadTaskDetail() // 重新加载任务详情
    } else {
      throw new Error('拒绝申请失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '拒绝申请失败')
    }
  }
}

const handleApplyTask = async () => {
  try {
    await ElMessageBox.confirm('确定要申请该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 显示加载状态
    loading.value = true;
    
    console.log('正在申请任务:', task.value.id);
    const response = await applyTask(task.value.id)
    console.log('申请任务响应:', response);
    
    if (response && (response.data === true || response.data === 'true' || response.code === 200)) {
      ElMessage.success('申请成功')
      // 更新本地状态，避免重新加载时间过长
      task.value.isApplied = true
      task.value.applicationStatus = 'pending'
      
      // 在申请列表中添加自己的申请记录（如果后端没有返回）
      const currentUser = {
        id: localStorage.getItem('applicationId') || Date.now(),
        workerId: localStorage.getItem('userId'),
        workerName: localStorage.getItem('username') || '当前用户',
        status: 'pending',
        createTime: new Date().toISOString()
      }
      
      // 如果申请列表中没有自己的申请，添加一个
      if (!applications.value.some(app => app.workerId === currentUser.workerId)) {
        applications.value.push(currentUser)
      }
      
      // 自动发送打招呼消息给企业用户
      if (task.value.companyId) {
        const messageData = {
          receiverId: Number(task.value.companyId),
          taskId: Number(task.value.id),
          content: `您好，我对您发布的任务"${task.value.title}"很感兴趣，我已提交了申请，期待您的回复！`
        }
        
        try {
          await sendMessage(messageData)
          console.log('自动发送打招呼消息成功')
        } catch (msgError) {
          console.error('自动发送打招呼消息失败:', msgError)
          // 不中断流程，继续处理
        }
      }
      
      // 重新加载任务详情，获取最新数据
      loadTaskDetail()
    } else {
      throw new Error(response?.message || '申请失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '申请任务失败')
    }
  } finally {
    loading.value = false;
  }
}

const handleCancelApplyTask = async () => {
  try {
    // 检查申请状态
    if (task.value.applicationStatus !== 'pending') {
      ElMessage.warning(`只能取消待处理的申请，当前申请状态为：${getApplicationStatusText(task.value.applicationStatus)}`);
      return;
    }
    
    await ElMessageBox.confirm('确定要取消申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true;
    
    const response = await cancelApplyTask(task.value.id)
    if (response && (response.data === true || response.data === 'true' || response.code === 200)) {
      ElMessage.success('已取消申请')
      
      // 更新本地状态，避免重新加载时间过长
      task.value.isApplied = false;
      task.value.applicationStatus = null;
      
      // 自动发送消息通知企业用户已取消申请
      if (task.value.companyId) {
        const messageData = {
          receiverId: Number(task.value.companyId),
          taskId: Number(task.value.id),
          content: `您好，我已取消对任务"${task.value.title}"的申请。`
        }
        
        try {
          await sendMessage(messageData)
          console.log('自动发送取消申请通知消息成功')
        } catch (msgError) {
          console.error('自动发送取消申请通知消息失败:', msgError)
          // 不中断流程
        }
      }
      
      // 从申请列表中移除自己的申请
      const userId = localStorage.getItem('userId')
      if (applications.value && applications.value.length > 0) {
        applications.value = applications.value.filter(app => app.workerId !== userId)
      }
      
      // 重新加载任务详情
      loadTaskDetail()
    } else {
      throw new Error('取消申请失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '取消申请失败')
    }
  } finally {
    loading.value = false;
  }
}

const openMessageDialog = () => {
  // 重置消息表单
  messageForm.value = createDefaultMessageForm();
  messageForm.value.taskId = task.value.id;
  
  // 如果是零工用户，设置消息接收者为任务发布者
  if (isWorkerUser.value && task.value) {
    messageForm.value.receiverId = Number(task.value.companyId);
    console.log(`零工用户消息接收者设置为企业ID: ${task.value.companyId}`);
  } else if (isCompanyUser.value && isTaskOwner.value) {
    // 企业用户发送消息时，默认选择第一个申请者（如果有）
    if (applications.value && applications.value.length > 0) {
      const firstApplicant = applications.value[0];
      messageForm.value.receiverId = Number(firstApplicant.workerId);
      console.log(`企业用户消息接收者设置为零工ID: ${firstApplicant.workerId}`);
    } else {
      console.warn('没有申请者可以发送消息');
      ElMessage.warning('当前没有申请者，无法发送消息');
      return; // 不显示对话框
    }
  }
  
  console.log('消息表单初始化:', JSON.stringify(messageForm.value));
  
  // 打开对话框
  messageDialogVisible.value = true;
}

const handleSendMessage = () => {
  if (!messageForm.value.content.trim()) {
    ElMessage.warning('消息内容不能为空');
    return;
  }
  
  if (!messageForm.value.receiverId) {
    // 根据用户类型给出具体提示
    if (isWorkerUser.value) {
      ElMessage.warning('无法找到任务发布者信息，无法发送消息');
    } else if (isCompanyUser.value) {
      ElMessage.warning('当前没有申请者，无法发送消息');
    } else {
      ElMessage.warning('请选择消息接收者');
    }
    return;
  }
  
  if (!messageForm.value.taskId) {
    ElMessage.warning('任务ID不能为空');
    return;
  }

  // 确保ID是数字类型
  const messageData = {
    receiverId: Number(messageForm.value.receiverId),
    taskId: Number(messageForm.value.taskId),
    content: messageForm.value.content.trim()
  };
  
  // 验证转换后的数据
  if (isNaN(messageData.receiverId)) {
    console.error('接收者ID无效:', messageForm.value.receiverId);
    ElMessage.error('接收者ID格式无效');
    return;
  }

  if (isNaN(messageData.taskId)) {
    console.error('任务ID无效:', messageForm.value.taskId);
    ElMessage.error('任务ID格式无效');
    return;
  }
  
  console.log('发送消息数据:', JSON.stringify(messageData));
  
  loading.value = true;
  
  sendMessage(messageData)
    .then(response => {
      loading.value = false;
      console.log('消息发送响应:', response);
      
      // 添加更详细的响应检查
      if (response === null || response === undefined) {
        throw new Error('服务器响应为空');
      }
      
      if (typeof response === 'string') {
        try {
          response = JSON.parse(response);
          console.log('解析字符串响应:', response);
        } catch (e) {
          console.error('响应不是有效的JSON:', e);
          throw new Error('服务器响应格式有误');
        }
      }
      
      if (response && (response.success || response.code === 200)) {
        ElMessage.success('消息发送成功');
        messageDialogVisible.value = false;
        messageForm.value = createDefaultMessageForm();
      } else {
        const errorMsg = response?.message || '消息发送失败';
        console.error('发送消息失败:', errorMsg, response);
        ElMessage.error(errorMsg);
      }
    })
    .catch(error => {
      loading.value = false;
      console.error('发送消息错误:', error);
      ElMessage.error('发送消息失败: ' + (error.message || '未知错误'));
    });
};

const getReceiverName = () => {
  if (isWorkerUser.value && task.value) {
    return task.value.companyName || '发布企业';
  } else if (isCompanyUser.value && isTaskOwner.value) {
    // 查找对应的申请者姓名
    if (messageForm.value.receiverId) {
      const applicant = applications.value.find(app => app.workerId === messageForm.value.receiverId);
      return applicant ? applicant.workerName : '申请者';
    }
  }
  return '消息接收者';
}

// 零工用户标记任务完成
const handleWorkerCompleteTask = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要标记任务为已完成吗？提交后将等待企业确认。', 
      '提示', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    
    const response = await workerCompleteTask(task.value.id)
    if (response && (response.data === true || response.data === 'true' || response.code === 200)) {
      ElMessage.success('已提交任务完成，等待企业确认')
      
      // 更新本地状态
      task.value.status = 'pending_completion'
      
      // 自动发送消息给企业
      if (task.value.companyId) {
        const messageData = {
          receiverId: Number(task.value.companyId),
          taskId: Number(task.value.id),
          content: `您好，我已完成任务"${task.value.title}"，请查看并确认。`
        }
        
        try {
          await sendMessage(messageData)
          console.log('自动发送任务完成通知消息成功')
        } catch (msgError) {
          console.error('自动发送任务完成通知消息失败:', msgError)
          // 不中断流程
        }
      }
      
      // 重新加载任务详情
      loadTaskDetail()
    } else {
      throw new Error(response?.message || '标记任务完成失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '标记任务完成失败')
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadTaskDetail()
})
</script>

<style scoped>
.task-detail-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.task-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-info {
  margin-bottom: 20px;
}

.salary {
  color: #e6a23c;
  font-weight: bold;
  font-size: 1.2em;
}

.task-content {
  white-space: pre-line;
}

.user-operations {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #ebeef5;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  position: relative;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.task-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.applications-card, .application-status-card, .timeline-card {
  margin-bottom: 20px;
}

.application-item {
  padding: 10px 0;
}

.application-item-info p {
  margin: 5px 0;
}

.application-actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

.task-status-info {
  margin-bottom: 15px;
}

.mb-10 {
  margin-bottom: 10px;
}

.application-status {
  padding: 10px 0;
}

.message-receiver-tag {
  padding: 5px 10px;
  border-radius: 4px;
  background-color: #f0f9eb;
  color: #67c23a;
  font-weight: bold;
}

.message-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  margin-left: 5px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-row {
    display: flex;
    flex-direction: column;
  }
  
  .el-col {
    width: 100% !important;
    max-width: 100% !important;
    flex: 0 0 100% !important;
  }
}

.task-application-status-card {
  margin-bottom: 20px;
}

.task-application-status .el-descriptions {
  width: 100%;
}

.task-application-status .el-tag {
  margin: 0 5px;
}

.mt-5 {
  margin-top: 5px;
}

.ml-5 {
  margin-left: 5px;
}

.ml-10 {
  margin-left: 10px;
}

.application-item-title {
  display: flex;
  align-items: center;
}
</style> 